

import { Flex, Form, FormInstance, Button, message } from '@/components/base';
import { useNavigate } from 'react-router-dom';
import React from 'react';
import { BigNumber } from 'bignumber.js';
import * as apis from '@/apis';
import { Controller } from '@/controller';
import dayjs from 'dayjs';
import * as UI from '../../ui'


/** 新建订单 */
export function CreateOrder() {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [values, setValues] = React.useState<any>();
    useAutoCalculate(form, values);
    useAutoOrderNo(form);

    const onCreate = React.useCallback(async () => {
        const values = await form.validateFields();
        await apis.order.add.post(values);
        message.success('操作成功');
        navigate(-1);
    }, [form, navigate]);

    return (
        <Form form={form} layout='vertical' onValuesChange={(_, v) => { setValues(v) }} >
            <div>
                <Flex justify='flex-end' gap={10} align='center' style={{ marginBottom: 20 }} >
                    <Button onClick={() => { navigate(-1) }} >返回</Button>
                    <Button type='primary' onClick={onCreate} >创建</Button>
                </Flex>
                <UI.FormItem />
            </div>
        </Form>
    )
}

/** 自动计算-单价、总价、商务人天 */
function useAutoCalculate(form: FormInstance<any>, values?: any) {
    React.useEffect(() => {
        const price = values?.price;
        const businessDay = form.getFieldValue('businessDay');
        if (price && businessDay) {
            form.setFieldsValue({
                amount: new BigNumber(price).multipliedBy(businessDay).toNumber(),
            });
        }
    }, [values?.price, form]);

    React.useEffect(() => {
        const businessDay = values?.businessDay;
        const price = form.getFieldValue('price');
        if (price && businessDay) {
            form.setFieldsValue({
                amount: new BigNumber(price).multipliedBy(businessDay).toNumber(),
            });
        }
    }, [values?.businessDay, form]);
}

/** 自动生成 orderNo */
function useAutoOrderNo(form: FormInstance<any>) {
    React.useEffect(() => {
        if (!form) return;
        apis.order.generateName.get().then(data => {
            const s = Controller.instance;
            form.setFieldsValue({
                orderNo: `${s.company === 'hh' ? 'CD' : 'CQ'}-${s.userInfo?.job_number}-${dayjs().format('YYYYMMDD')}-${unToSt(`${data + 1}`)}`,
            });
        });
    }, [form]);
}

function unToSt(value: string) {
    if (value.length < 3) {
        return unToSt(`0${value}`)
    } else {
        return value;
    }
}